package com.woniuxy.ptapp.service.impl;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.C;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.commons.util.BeanCopyUtil;
import com.woniuxy.commons.util.DateUtil;
import com.woniuxy.commons.util.Result;
import com.woniuxy.ptapp.common.exception.EnumExceptionCode;
import com.woniuxy.ptapp.common.exception.WoniuxyException;
import com.woniuxy.ptapp.common.param.LoginUser;
import com.woniuxy.ptapp.common.util.FinMessageIdByAccountId;
import com.woniuxy.ptapp.common.util.GetLogingUser;
import com.woniuxy.ptapp.infra.CommentInfoDao;
import com.woniuxy.ptapp.infra.model.ClassesOrder;
import com.woniuxy.ptapp.infra.model.CommentAttachment;
import com.woniuxy.ptapp.infra.model.CommentInfo;
import com.woniuxy.ptapp.service.ClassesOrderService;
import com.woniuxy.ptapp.service.CommentAttachmentService;
import com.woniuxy.ptapp.service.CommentInfoService;
import com.woniuxy.ptapp.service.dto.CommentDto;
import com.woniuxy.ptapp.service.dto.ShowEvaluationDto;
import com.woniuxy.userapp.client.StudentClient;
import com.woniuxy.userapp.client.VenueClient;
import com.woniuxy.userapp.client.param.StudentInfo;
import com.woniuxy.userapp.client.param.VenueInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 评价信息表 服务实现类
 * </p>
 *
 * @author wangdong
 * @since 2022-07-30
 */
@Service
public class CommentInfoServiceImpl extends ServiceImpl<CommentInfoDao, CommentInfo> implements CommentInfoService {

    @Resource
    ClassesOrderService classesOrderService;

    @Resource
    CommentAttachmentService commentAttachmentService;

    @Resource
    GetLogingUser getLogingUser;

    @Resource
    StudentClient studentClient;

    @Resource
    VenueClient venueClient;

    @Resource
    FinMessageIdByAccountId findUtil;

    @Override
    public void appraise(CommentDto commentDto) {

        //获取登录的信息
        LoginUser logingUser = getLogingUser.getLogingUser();
        //判断该订单id是否存在
        ClassesOrder classesOrder = classesOrderService.getOne(new QueryWrapper<ClassesOrder>().eq("id", commentDto.getClassesOrderId()));
        if (null == classesOrder) {
            throw new WoniuxyException(EnumExceptionCode.getClassesOrderFail.getCode(), EnumExceptionCode.getClassesOrderFail.getMessage());
        }
        //判断改订单是否是登录用户自己的
        Integer studentId = findUtil.findStudentId(logingUser.getLoginId());
        QueryWrapper<ClassesOrder> commentInfoQueryWrapper = new QueryWrapper<>();
        commentInfoQueryWrapper.eq("id", commentDto.getClassesOrderId());
        commentInfoQueryWrapper.eq("student_id",studentId);
        ClassesOrder one = classesOrderService.getOne(commentInfoQueryWrapper);
        if(one==null){
            throw new WoniuxyException(EnumExceptionCode.ClaessIdWrong.getCode(),EnumExceptionCode.ClaessIdWrong.getMessage());
        }
        //订单状态只有已完成才可以评价
        if(one.getState()!=1){
            throw new WoniuxyException(EnumExceptionCode.TheStateCantEvaluation.getCode(),EnumExceptionCode.TheStateCantEvaluation
                    .getMessage());
        }
        //判断该订单是否评价
        CommentInfo comment = this.getOne(new QueryWrapper<CommentInfo>().eq("classes_order_id",commentDto.getClassesOrderId()));
        if (comment != null) {
            throw new WoniuxyException(EnumExceptionCode.OrderHasBeenEvaluated.getCode(), EnumExceptionCode.OrderHasBeenEvaluated.getMessage());
        }
        CommentInfo commentInfo = BeanCopyUtil.copyObject(commentDto, CommentInfo.class);
        commentInfo.setVenueId(classesOrder.getVenueId());
        if (commentDto.getCommontPhoto() == null || commentDto.getCommontPhoto().size() <= 0) {
            commentInfo.setPictureFlag(0);
        }else{
            commentInfo.setPictureFlag(1);
        }
        commentInfo.setUserPhoto("https://wangdongfoodsystem.oss-cn-chengdu.aliyuncs.com/6e5e8b67-86c6-409c-a02e-3528781306ea.webp");
        commentInfo.setUserName(logingUser.getLoginName());
        commentInfo.setCommentManId(logingUser.getLoginId());
        commentInfo.setDate(DateUtil.timeFormatString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
        boolean save = this.save(commentInfo);
        if (!save) {
            throw new WoniuxyException(EnumExceptionCode.commonentSaveFail.getCode(), EnumExceptionCode.commonentSaveFail.getMessage());
        }
        //存入评价附件 有评价图片才存入附件表
        if(commentDto.getCommontPhoto() != null && commentDto.getCommontPhoto().size() > 0){
            List<CommentAttachment> commentAttachments = BeanCopyUtil.copyList(commentDto.getCommontPhoto(), CommentAttachment.class);
            for (CommentAttachment commentAttachment : commentAttachments) {
                commentAttachment.setCommentid(commentInfo.getId());
            }
            boolean b = commentAttachmentService.saveBatch(commentAttachments);
            if (!b) {
                throw new WoniuxyException(EnumExceptionCode.AttachmentSaveFail.getCode(), EnumExceptionCode.AttachmentSaveFail.getMessage());
            }
            //修改订单评价状态
            classesOrder.setEvaluate(1);
            boolean b1 = classesOrderService.saveOrUpdate(classesOrder);
            if(!b1){
              throw new WoniuxyException(EnumExceptionCode.ChangeOrederStateFail.getCode(),EnumExceptionCode.ChangeOrederStateFail.getMessage() );
            }
        }
    }

    @Override
    public void reply(Integer classesOrderId, String reply) {
        LoginUser logingUser = getLogingUser.getLogingUser();
        //判断该订单id是否存在
        ClassesOrder classesOrder = classesOrderService.getOne(new QueryWrapper<ClassesOrder>().eq("id", classesOrderId));
        //判断回复订单是否是该场馆
        Integer venueId = findUtil.findVenueId(logingUser.getLoginId());
        QueryWrapper<ClassesOrder> classesOrderQueryWrapper = new QueryWrapper<>();
        classesOrderQueryWrapper.eq("venue_id",venueId);
        classesOrderQueryWrapper.eq("id",classesOrderId);
        ClassesOrder one = classesOrderService.getOne(classesOrderQueryWrapper);
        if(one==null){
            throw new WoniuxyException(EnumExceptionCode.ClaessIdWrong.getCode(),EnumExceptionCode.ClaessIdWrong.getMessage());
        }
        //查询订单是否已经回复
        CommentInfo comment = this.getOne(new QueryWrapper<CommentInfo>().eq("classes_order_id", classesOrderId));
        if (comment.getReplayFlag() == 1) {
            throw new WoniuxyException(EnumExceptionCode.EvaluationHasBeenReplyTo.getCode(), EnumExceptionCode.EvaluationHasBeenReplyTo.getMessage());
        }
        comment.setReplay(reply);
        comment.setReplayFlag(1);
        boolean b = this.saveOrUpdate(comment);
        if (!b) {
            throw new WoniuxyException(EnumExceptionCode.RespondTOfailure.getCode(), EnumExceptionCode.RespondTOfailure.getMessage());
        }

    }

    @Override
    public List<ShowEvaluationDto> showEvaluation() {
        LoginUser logingUser = getLogingUser.getLogingUser();
        List<ShowEvaluationDto> showEvaluationDtos = new ArrayList<>();
        if (logingUser.getLoginRole() == 2) {
            Integer coachId = findUtil.findCoachId(logingUser.getLoginId());
            //教练查询对于的订单评价
            List<ClassesOrder> classesOrders = classesOrderService.list(new QueryWrapper<ClassesOrder>().eq("coach_id", coachId));

            if (null == classesOrders || classesOrders.size() <= 0) {
                throw new WoniuxyException(EnumExceptionCode.NoHaveClassesOrder.getCode(), EnumExceptionCode.NoHaveClassesOrder
                        .getMessage());
            }
            List<ClassesOrder> classesOrderList = classesOrders.stream().filter(m -> m.getEvaluate() == 1).collect(Collectors.toList());
            List<Integer> classesOrderIds = classesOrderList.stream().map(m -> m.getId()).collect(Collectors.toList());
            System.out.println(classesOrderIds);
            for (Integer classesOrderId : classesOrderIds) {
                CommentInfo commentInfo = this.getOne(new QueryWrapper<CommentInfo>().eq("classes_order_id", classesOrderId));
                if(null==commentInfo){
                    throw new WoniuxyException(EnumExceptionCode.Noevaluation.getCode(), EnumExceptionCode.Noevaluation
                            .getMessage());
                }
                if(commentInfo.getDeleteFlag()==0){
                    ShowEvaluationDto showEvaluationDto = BeanCopyUtil.copyObject(commentInfo, ShowEvaluationDto.class);
                    List<CommentAttachment> commentAttachments = commentAttachmentService.list(new QueryWrapper<CommentAttachment>().eq("commentId", commentInfo.getId()));
                    List<String> collect = commentAttachments.stream().map(m -> m.getFilepath()).collect(Collectors.toList());
                    showEvaluationDto.setCommnetPhoto(collect);
                    showEvaluationDtos.add(showEvaluationDto);
                }
            }
        } else if (logingUser.getLoginRole() == 3) {
            Integer studentId = findUtil.findStudentId(logingUser.getLoginId());
            List<ClassesOrder> classesOrders = classesOrderService.list(new QueryWrapper<ClassesOrder>().eq("student_id", studentId));
            if (null == classesOrders || classesOrders.size() <= 0) {
                throw new WoniuxyException(EnumExceptionCode.NoHaveClassesOrder.getCode(), EnumExceptionCode.NoHaveClassesOrder
                        .getMessage());
            }
            System.out.println(classesOrders);
            System.out.println("查询学员订单=========================");
            List<ClassesOrder> classesOrderList = classesOrders.stream().filter(m -> m.getEvaluate() == 1).collect(Collectors.toList());
            List<Integer> classesOrderIds = classesOrderList.stream().map(m -> m.getId()).collect(Collectors.toList());
            System.out.println(classesOrderIds+"查询学员所有订单的id");
            for (Integer classesOrderId : classesOrderIds) {
                QueryWrapper<CommentInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("classes_order_id", classesOrderId);
                CommentInfo commentInfo = this.getOne(queryWrapper);
                if(null==commentInfo){
                    throw new WoniuxyException(EnumExceptionCode.Noevaluation.getCode(), EnumExceptionCode.Noevaluation
                            .getMessage());
                }
                if(commentInfo.getDeleteFlag()==0){
                    ShowEvaluationDto showEvaluationDto = BeanCopyUtil.copyObject(commentInfo, ShowEvaluationDto.class);
                    List<CommentAttachment> commentAttachments = commentAttachmentService.list(new QueryWrapper<CommentAttachment>().eq("commentId", commentInfo.getId()));
                    List<String> collect = commentAttachments.stream().map(m -> m.getFilepath()).collect(Collectors.toList());
                    showEvaluationDto.setCommnetPhoto(collect);
                    showEvaluationDtos.add(showEvaluationDto);
                }

            }
        } else if (logingUser.getLoginRole() == 1) {
            Integer venueId = findUtil.findVenueId(logingUser.getLoginId());
            List<CommentInfo> commentInfos = this.list(new QueryWrapper<CommentInfo>().eq("venue_id", venueId));
            if(null==commentInfos){
                throw new WoniuxyException(EnumExceptionCode.Noevaluation.getCode(), EnumExceptionCode.Noevaluation
                        .getMessage());
            }
            System.out.println(commentInfos);
            List<CommentInfo> collect1 = commentInfos.stream().filter(m -> m.getDeleteFlag() == 0).collect(Collectors.toList());
            System.out.println(collect1);
            List<ShowEvaluationDto> evaluationDtos = BeanCopyUtil.copyList(collect1, ShowEvaluationDto.class);
            for (ShowEvaluationDto evaluationDto : evaluationDtos) {
                List<CommentAttachment> commentAttachments = commentAttachmentService.list(new QueryWrapper<CommentAttachment>().eq("commentId", evaluationDto.getId()));
                List<String> collect = commentAttachments.stream().map(m -> m.getFilepath()).collect(Collectors.toList());
                evaluationDto.setCommnetPhoto(collect);
                showEvaluationDtos.add(evaluationDto);
            }

        }
        if(showEvaluationDtos==null||showEvaluationDtos.size()<=0){
            throw new WoniuxyException(EnumExceptionCode.Noevaluation.getCode(),EnumExceptionCode.Noevaluation.getMessage() );
        }
        return showEvaluationDtos;

    }
}
